package com.yaowk.common.server.exception;

import com.yaowk.common.api.BaseException;
import com.yaowk.common.api.model.result.Result;
import com.yaowk.common.api.utils.ResultUtils;
import com.yaowk.eoms.api.NotifyApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@ControllerAdvice(annotations = RestController.class)
@ResponseBody
public class BaseExceptionAdvice {

    @Value("${com.yaowk.web.notifyEnable:true}")
    private boolean notifyEnable;

    @Autowired(required = false)
    private NotifyApi notifyApi;

    @ExceptionHandler(BaseException.class)
    public Result baseException(BaseException e) {
        doException(e);
        return ResultUtils.result(Result.Code.FAIL.getValue(), e.getMessage());
    }

    private void doException(Throwable e) {
        log.info("", e);
        if (notifyEnable) {
            try {
                notifyApi.send(e.getMessage());
            } catch (Throwable throwable) {
                log.info("--异常通知失败--", throwable);
            }
        }
    }
}
